#!/usr/bin/env node

const data = require('./blog-demo/data.js').chapterList,
      Koa = require('koa'),
      server = require('koa-static'),
      fs = require('fs');
const app = new Koa();

if(!fs.existsSync('./blog-demo/chapters.html')){
  console.error('chapters.html文件不存在！');
  process.exit(1);
}
const html = fs.readFileSync('./blog-demo/chapters.html').toString('utf8');

data.sort((a,b)=>{
  let val1 = a.publishTimer.split('-').join('');
  let val2 = b.publishTimer.split('-').join('');
  return val2 - val1;
});

app.use(server('./blog-demo/'));

app.use((ctx, next)=>{
  if(ctx.request.url === '/'){
    ctx.type = 'text/html';
    ctx.body = html;
  }
  next();
});
app.use((ctx, next)=>{
  if(ctx.request.url === '/getlist'){
    ctx.body = JSON.stringify(data);
  }
});

app.listen(8080);
